import streamlit as st
# from st_audiorec import st_audiorec
# from audio_recorder_streamlit import audio_recorder
from audiorecorder import audiorecorder

st.set_page_config(
    page_title="ChatDemo-演示",
    page_icon=":robot:",
    layout="wide"
)

st.title("ChatDemo")

if "history" not in st.session_state:
    st.session_state.history = []

# 设置max_length、top_p和temperature
max_length = st.sidebar.slider("max_length", 0, 32768, 8192, step=1)
top_p = st.sidebar.slider("top_p", 0.0, 1.0, 0.8, step=0.01)
temperature = st.sidebar.slider("temperature", 0.0, 1.0, 0.6, step=0.01)

# 清理会话历史
buttonClean = st.sidebar.button("清理会话历史", key="clean")
if buttonClean:
    st.session_state.history = []
    st.session_state.past_key_values = None
    st.rerun()

# 渲染聊天历史记录
for i, message in enumerate(st.session_state.history):
    if message["role"] == "user":
        with st.chat_message(name="user", avatar="user"):
            st.markdown(message["content"])
    else:
        with st.chat_message(name="assistant", avatar="assistant"):
            st.markdown(message["content"])

# 输入框和输出框
with st.chat_message(name="user", avatar="user"):
    input_placeholder = st.empty()
with st.chat_message(name="assistant", avatar="assistant"):
    message_placeholder = st.empty()

# 获取用户输入
user_audio_input = audiorecorder("Click to record", "Click to stop recording")

if user_audio_input is not None:
    st.audio(user_audio_input.export().read())
    user_audio_input.export("input.wav", format='audio/wav')
    # 调用识别接口
    prompt_text="调用识别接口返回结果"

    # 如果用户输入了内容,则生成回复
    if prompt_text:
        input_placeholder.markdown(prompt_text)
        history = st.session_state.history
        past_key_values = st.session_state.past_key_values
        # for response, history, past_key_values in model.stream_chat(
        #     tokenizer,
        #     prompt_text,
        #     history,
        #     past_key_values=past_key_values,
        #     max_length=max_length,
        #     top_p=top_p,
        #     temperature=temperature,
        #     return_past_key_values=True,
        # ):
        #     message_placeholder.markdown(response)

        # 更新历史记录和past key values
        st.session_state.history = history
        st.session_state.past_key_values = past_key_values
